import { CoolController, BaseController } from '@cool-midway/core';
import { OrdersEntity } from '../../entity/orders';
import { Body, Inject, Post, Provide } from '@midwayjs/decorator';
import { EXCEL_MAP } from '../../contanst/orders';
import { OrdersService } from '../../service/orders';
import { Repository } from 'typeorm';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { OrdersProductsMapsService } from '../../service/ordersProductsMap';
import moment = require('moment');

@Provide()
@CoolController({
  api: ['add', 'delete', 'update', 'info', 'list', 'page'],
  entity: OrdersEntity,
  listQueryOp: {
    fieldEq: ['data_date'],
    keyWordLikeFields: ['store_name', 'order_number'],
    where: async () => {
      return [['status != :status', { status: '已关闭' }]];
    },
  },
  pageQueryOp: {
    fieldEq: ['data_date'],
    keyWordLikeFields: ['store_name', 'order_number'],
    where: async () => {
      return [['status != :status', { status: '已关闭' }]];
    },
  },
})
export class APIController extends BaseController {
  @InjectEntityModel(OrdersEntity)
  ordersEntity: Repository<OrdersEntity>;

  @Inject()
  ordersService: OrdersService;

  @Inject()
  ordersProductsMapService: OrdersProductsMapsService;
  @Post('/import')
  async import(
    @Body('list') data,
    @Body('store_name') store_name,
    @Body('data_date') data_date
  ) {
    const records: any[] = [];
    const mapRecords: any[] = [];
    data.forEach(item => {
      const record: any = {};
      const mapRecord: any = {};
      Object.keys(EXCEL_MAP).forEach(key => {
        if (EXCEL_MAP[key] === 'product_code') {
          const arr = item[key]?.split?.('-') || [];
          const product_specification =
            parseInt(arr.at(-1)?.replace?.(/\t/g, '')) || null;
          record['product_code'] = arr
            .filter((i, k) => k !== arr.length - 1)
            ?.join('')
            ?.replace?.(/\t/g, '');
          record['product_specification'] = product_specification;
          record['product_unit'] = arr.at(-1).replace(/[0-9]+/g, '');
          mapRecord.product_specification = record['product_specification'];
          mapRecord.product_unit = record['product_unit'];
          mapRecord.product_code = record['product_code'];
        } else {
          record[EXCEL_MAP[key]] = item[key]?.replace?.(/\t/g, '') || item[key];
          mapRecord[EXCEL_MAP[key]] = record[EXCEL_MAP[key]];
        }
      });
      record.store_name = store_name;
      record.data_date = moment(data_date).format('YYYY-MM-DD');
      mapRecord.store_name = store_name;
      mapRecord.data_date = moment(data_date).format('YYYY-MM-DD');
      records.push(record);
      mapRecords.push(mapRecord);
    });

    this.ordersService.upsert(records);
    this.ordersProductsMapService.upsert(mapRecords);
    return this.ok();
  }
}
